package program;

import avenue.MyWindowEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.List;
import javax.persistence.EntityManager;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import model.DBManager;
import model.Program;
import model.ProgramRate;
import model.Station;

public class EditProgramForm extends javax.swing.JFrame {

    public EditProgramForm() {
        em = DBManager.em;
        if ( !em.getTransaction().isActive()){
            em.getTransaction().begin();
        }
        initComponents();
    }
    
    public EditProgramForm(Program p,  boolean readOnly) {
        em = DBManager.em;
        program1=p;
        this.readOnly = readOnly;
        if ( !(em.getTransaction().isActive()) ){
            em.getTransaction().begin();
        }
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        station2 = new model.Station();
        program2 = program1;
        stationQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("select s from Station s");
        stationList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(stationQuery.getResultList());
        stationBoxRenderer1 = new avenue.StationBoxRenderer();
        programRateQuery = em.createQuery("select pr from ProgramRate pr where pr.stationId=:station and pr.programId=:program").setParameter("station", station2).setParameter("program", program2);
        programRateList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(programRateQuery.getResultList());
        stationLabel = new javax.swing.JLabel();
        separator = new javax.swing.JSeparator();
        diodiaLabel = new javax.swing.JLabel();
        programDescriptionLabel = new javax.swing.JLabel();
        cancelButton = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();
        programDescriptionTF = new javax.swing.JTextField();
        stationComboBox = new javax.swing.JComboBox();
        programRatesScrollPane = new javax.swing.JScrollPane();
        programRatesTable = new javax.swing.JTable();
        programNameLabel = new javax.swing.JLabel();
        programNameTF = new javax.swing.JTextField();
        programPayLimitLabel = new javax.swing.JLabel();
        programPayLimitTF = new javax.swing.JTextField();

        stationBoxRenderer1.setText("stationBoxRenderer1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Διαχείριση Προγράμματος");

        stationLabel.setText("Σταθμός: ");

        diodiaLabel.setText("Διόδια που εισπράτονται ανά κατηγορία οχήματος");

        programDescriptionLabel.setText("Περιγραφή:");

        cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        cancelButton.setText("Ακυρο");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        saveButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/save.gif"))); // NOI18N
        saveButton.setText("Αποθήκευση");
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, program2, org.jdesktop.beansbinding.ELProperty.create("${description}"), programDescriptionTF, org.jdesktop.beansbinding.BeanProperty.create("text"), "programDescription");
        bindingGroup.addBinding(binding);

        stationComboBox.setRenderer(stationBoxRenderer1);

        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, stationList, stationComboBox, "stationBoxBinding");
        bindingGroup.addBinding(jComboBoxBinding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, station2, org.jdesktop.beansbinding.ObjectProperty.create(), stationComboBox, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"), "stationBinding");
        bindingGroup.addBinding(binding);

        stationComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                stationComboBoxActionPerformed(evt);
            }
        });

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, programRateList, programRatesTable, "rate");
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${categoryId}"));
        columnBinding.setColumnName("Category Id");
        columnBinding.setColumnClass(model.VehicleCategory.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${rate}"));
        columnBinding.setColumnName("Rate");
        columnBinding.setColumnClass(java.math.BigDecimal.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        programRatesScrollPane.setViewportView(programRatesTable);

        programNameLabel.setText("Όνομα:");

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, program2, org.jdesktop.beansbinding.ELProperty.create("${name}"), programNameTF, org.jdesktop.beansbinding.BeanProperty.create("text"), "programName");
        bindingGroup.addBinding(binding);

        programPayLimitLabel.setText("Άνω όριο μηνιαίων χρεωθέντων διελεύσεων:");

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, program2, org.jdesktop.beansbinding.ELProperty.create("${payLimit}"), programPayLimitTF, org.jdesktop.beansbinding.BeanProperty.create("text"), "payLimit");
        bindingGroup.addBinding(binding);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(stationLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(stationComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(49, 49, 49)
                        .addComponent(programNameLabel)
                        .addGap(18, 18, 18)
                        .addComponent(programNameTF, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(programDescriptionLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(programDescriptionTF, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addComponent(separator)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(diodiaLabel)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(cancelButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(saveButton))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(programRatesScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 392, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(28, 28, 28)
                                .addComponent(programPayLimitLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(programPayLimitTF, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 125, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(stationLabel)
                    .addComponent(programDescriptionLabel)
                    .addComponent(programDescriptionTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(stationComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(programNameLabel)
                    .addComponent(programNameTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(separator, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(1, 1, 1)
                .addComponent(diodiaLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(programRatesScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(programPayLimitLabel)
                        .addComponent(programPayLimitTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveButton)
                    .addComponent(cancelButton))
                .addContainerGap(116, Short.MAX_VALUE))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        
        // Διαχείριση παραθύρων
        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED,false);
        for (WindowListener l : this.getWindowListeners()) {
            l.windowClosed(we);
        }
        this.setVisible(false); 
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        
        // Έλεγχος των πληροφοριών του νέου προγράμματος
        if (programNameTF.getText().equals("")) { 
            JOptionPane.showMessageDialog(this, "Το όνομα του προγράμματος δεν μπορεί να είναι κενό.",
                                          "Σφάλμα",JOptionPane.ERROR_MESSAGE);
            return;
        } else if (programDescriptionTF.getText().equals("")) { 
            JOptionPane.showMessageDialog(this, "Η περιγραφή του προγράμματος δεν μπορεί να είναι κενή.",
                                          "Σφάλμα",JOptionPane.ERROR_MESSAGE);
            return;
        } else if (programPayLimitTF.getText().equals("")) { 
            JOptionPane.showMessageDialog(this, "Ο ανώτατος αριθμός μηνιαίων χρεώσεων δεν μπορεί να είναι κενός.",
                                          "Σφάλμα",JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        // Διαχείριση παραθύρων
        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED,true);
        for (WindowListener l : this.getWindowListeners()) {
            l.windowClosed(we);
        }
        this.setVisible(false); 
    }//GEN-LAST:event_saveButtonActionPerformed

    private void stationComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stationComboBoxActionPerformed

        if(stationList.size()>0 && stationComboBox.getSelectedIndex()!=-1){
            station1=(Station)(stationList.get(stationComboBox.getSelectedIndex()));
            programRateQuery = em.createQuery("select pr from ProgramRate pr where pr.stationId=:station and pr.programId=:program").setParameter("station", station1).setParameter("program", program2);
            //query2 = em.createQuery("select pr from ProgramRate pr ");
            List<ProgramRate> list3 = programRateQuery.getResultList();
            if (list3.size()>0){
                programRateList.clear();
                for (ProgramRate pr : list3){
                 programRateList.add(pr);  
               }
            } 
        }
    }//GEN-LAST:event_stationComboBoxActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel diodiaLabel;
    private model.Program program2;
    private javax.swing.JLabel programDescriptionLabel;
    private javax.swing.JTextField programDescriptionTF;
    private javax.swing.JLabel programNameLabel;
    private javax.swing.JTextField programNameTF;
    private javax.swing.JLabel programPayLimitLabel;
    private javax.swing.JTextField programPayLimitTF;
    private java.util.List<ProgramRate> programRateList;
    private javax.persistence.Query programRateQuery;
    private javax.swing.JScrollPane programRatesScrollPane;
    private javax.swing.JTable programRatesTable;
    private javax.swing.JButton saveButton;
    private javax.swing.JSeparator separator;
    private model.Station station2;
    private avenue.StationBoxRenderer stationBoxRenderer1;
    private javax.swing.JComboBox stationComboBox;
    private javax.swing.JLabel stationLabel;
    private java.util.List<Station> stationList;
    private javax.persistence.Query stationQuery;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    EntityManager em;
    ProgramRate pr;
    Program program1;
    Station station1;
    JFrame thisFrame;
    boolean readOnly;
}
